<html>
<head>
<script type="text/javascript" src="lib/3rdparty/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="lib/3rdparty/jquery.effects.core.min.js"></script>
<script type="text/javascript" src="engine.js"></script>
<script type="text/javascript" src="probe_manager.js"></script>
<script type="text/javascript" src="probe.js"></script>
<script type="text/javascript" src="queryURL.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">$(pluginInit);</script>
</head>
<body>
<script type="text/javascript">
const CORRECTION_FACTOR = 0.8;
//const ALERT_RATIO = 3;

var baseURL = 'http://search.twitter.com/search.json?';
var probeManager = new ProbeManager();
var localPort;
const extension = chrome.extension;
extension.onConnect.addListener(function(port) {
	console.assert(port.name == "social-media-monitoring");
	localPort = port;
	port.onMessage.addListener(function(msg) {
		console.log('BackgroundPage, onMessage:' + msg);
		  
		if (msg.probeTagChanged) {
			var probeTag = msg.probeTagChanged;
			loadTweets(probeTag);
		}
		if (msg.requestGeolocation) {
		  	requestGeoLocation();
		}
	});
});

function loadTweets(probeTag) {
	var query = new QueryURL(baseURL, probeTag);
	var url = query.getURL();
	loadLongTermTweetsPerMinute(url, probeTag);
	/*
	 * TODO: Needs to be refactored in next version...
	*/
	setTimeout ( function() { 
		loadCurrentTweetsPerMinute(url, probeTag)
	}
	, 800);
}

function loadLongTermTweetsPerMinute(queryURL, probeTag) {
	var timeString = 0;
	var resultNumber = 1000;	
	
	$.getJSON(queryURL + '&rpp=1&page=' + resultNumber, function(data) {
		if(data.results.length == 0) {
			resultNumber = setNextResultNumberCount(resultNumber);
			$.getJSON(queryURL + '&rpp=1&page=' + resultNumber, function(data) {
		 		if(data.results.length == 0) {
		 			resultNumber = setNextResultNumberCount(resultNumber);
					$.getJSON(queryURL + '&rpp=1&page=' + resultNumber, function(data) {
				   	 	if(data.results.length != 0) {
				   	 	console.log('Puhh finally found tweets for your keyword');
				   	 		processLongTermTweets(data, probeTag, resultNumber);
						}
						else {
							localPort.postMessage({update:probeTag});
							console.log("Seems like your keyword hasen't been tweeted yet!?");						
						}
					});
				}
				else {
					processLongTermTweets(data, probeTag, resultNumber);
				}
			});
		}
		else {
			processLongTermTweets(data, probeTag, resultNumber);
		}
	});	
}

function setNextResultNumberCount(resultNumber) {
	console.log('Less than a ' + resultNumber + ' tweets ever');
	resultNumber = resultNumber / 10;
	console.log('Now checking last: ' + resultNumber + 'results');
	return resultNumber;
}

function processLongTermTweets(data, probeTag, resultNumber) {
	console.log("Starting processing of long term Tweets...");
	var timeString = data.results[0].created_at;
	probeTag.longTermTweetsPerMin = calculateTweetsPerMinute(timeString, resultNumber);
	probeManager.setProbe(probeTag);
	console.log("Finished Long Term procesing.");
	localPort.postMessage({update:probeTag});
}

function loadCurrentTweetsPerMinute(queryURL, probeTag) {
	console.log('Starting loading current tweets per minute...');
	$.getJSON(queryURL + '&rpp=100&page=1', function(data) {
		if(data.results.length > 0) {
			var now = new Date();
			var fiveMinAgo = now.getTime() - (60000 * 5);
			var tweetDate = new Date(data.results[0].created_at);
			
			var index = 0;
			/*
			 * TODO: Replace this with better algorithm then O(n), week could use a binary search like algorithm with O(log n)?
			*/
			while(tweetDate > fiveMinAgo && index < 100) {
				var ts = new Date(data.results[index].created_at);
				tweetDate = ts.getTime();
				index++;

				var diff = tweetDate - fiveMinAgo;
				console.log(index + ' tweets already found' +
							'Tweet Date: ' + ts + 
							' FiveMinAgo: ' + new Date(fiveMinAgo) + 
							' Diff: ' + diff +
							diff < 0 ? 'Termination condition full filled, stop counting' : '');

			}
			var numberOfTweetsWithinOneMinute = index / 5;
			console.log('Current Tweet count per Minute: ' + numberOfTweetsWithinOneMinute);
			if(numberOfTweetsWithinOneMinute >= 20) {
				console.log('Oh, more than 20 Tweets/Minute, switching strategy. Taking last 100 tweets for calculation');
				var timeString = data.results[data.results.length - 1].created_at;
				var tweetsPerMinute = calculateTweetsPerMinute(timeString, data.results.length);

				updateCurrentTweetsPerMinute(tweetsPerMinute, probeTag);
			}
			else if (numberOfTweetsWithinOneMinute === 0) {
				console.log('No Short term tweets in one minute');
				var watchLastTweets = Math.floor(data.results.length / 10);
				console.log('Try calculating current tweets per Minute with the last ' + watchLastTweets + 'Tweets');
				var timeString = data.results[watchLastTweets].created_at;
				var tweetsPerMinute = calculateTweetsPerMinute(timeString, watchLastTweets);

				updateCurrentTweetsPerMinute(tweetsPerMinute, probeTag);
			}
			else {
				updateCurrentTweetsPerMinute(numberOfTweetsWithinOneMinute, probeTag);
			}
			probeManager.setProbe(probeTag);
			localPort.postMessage({update:probeTag});
		}
		else if(data.results.length === 0){
			probeTag.shortTermTweetsPerMin = 0;
			console.log("Keyword hasen't been tweeted in the last five  minutes");
		}
		else {
			probeTag.shortTermTweetsPerMin = '?';
			console.log('Error in loading tweets from server');
		}
	});	
}

function updateCurrentTweetsPerMinute(tweetsWithinOneMinute, probeTag) {
	probeTag.shortTermTweetsPerMin = tweetsWithinOneMinute * CORRECTION_FACTOR;
	console.log("Finished Current Term processing");

	

	if(tweetsWithinOneMinute > probeTag.longTermTweetsPerMin * settings.thresholdRatio) {//version 0.1.1
	//if(tweetsWithinOneMinute > probeTag.longTermTweetsPerMin * probeTag.thresholdRatio) { //version 2.0
	//if(tweetsWithinOneMinute > probeTag.longTermTweetsPerMin * ALERT_RATIO) { //version 0.1
		
		/*
		 * do something on new event
		 */
			onNewEvent(probeTag);
		 /*
		  * sent message to popup.html if popup.html is active
		  */
		  if(localPort){
			localPort.postMessage({alert:probeTag});
		  }
		console.log('Alert >=' + tweetsWithinOneMinute + 'Tweets/Min');
	}
}

function calculateTweetsPerMinute(timeString, resultCount) {
	console.log('Current tweet was created on: ' + timeString);
	var lastTweet = new Date(timeString);	
	var now = new Date();
	var timeDiffInMS = now - lastTweet;
	console.log('Time difference between now and tweet date in ms: ' + timeDiffInMS);
	var timePerTweetInMS = timeDiffInMS / resultCount + 0.0;
	console.log('Time per tweet in ms: ' + timePerTweetInMS);
	var numberOfTweetsWithinOneMinute = (1000 * 60) / timePerTweetInMS + 0.0;
	console.log('Tweets per minute: ' + numberOfTweetsWithinOneMinute);
	console.log('Rounded Avg of tweets per minute: ' + Math.round(numberOfTweetsWithinOneMinute));
	return numberOfTweetsWithinOneMinute;
}

function locationDetected(position) {
	  var latitude = position.coords.latitude;
	  var longitude = position.coords.longitude;
	  localPort.postMessage({onLocationResult:{latitude:position.coords.latitude,
		  								  longitude:position.coords.longitude}});	  
}

function locationError(msg) {
  var status = typeof msg == 'string' ? msg : "failed";
  console.log('Error getting HTML5 Geolocation:' + status);
  console.log('Now trying to get IPLocation...');
  var ipLocation = google.loader.ClientLocation;
  if(ipLocation !== null) {
	  console.log('Success getting IP Location');
	  localPort.postMessage({onLocationResult:{latitude:ipLocation.latitude,longitude:ipLocation.longitude}});
  }
  else {
	  console.log('Error getting IP Location, hello Mountain View');
  }
}

function requestGeoLocation(){
	if (navigator.geolocation) {
		console.log('Requesting HTML5 Geolocation...');
	  	navigator.geolocation.getCurrentPosition(locationDetected, locationError);
	} else {
		locationError('Geo location not supported! Geolocation is currently only supported in the dev channels Try start chrome with arguments: --enable geolocation');
	}
}

function getProbeManager() {
	return probeManager;
}

</script>
</body>
</html>